package com.zahb.qadx.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.model.TrainDataBean;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.skeleton.RecyclerViewSkeletonScreen;
import com.zahb.qadx.skeleton.Skeleton;
import com.zahb.qadx.ui.adapter.MyTrainAdapter;
import com.zahb.qadx.ui.view.decoration.MColorDrawable;
import com.zahb.qadx.ui.view.decoration.MDividerItemDecoration;
import com.zahb.qadx.util.CompatHelper;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.DisplayUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class MyTrainActivity extends BaseActivity implements OnRefreshLoadMoreListener {

    @BindView(R.id.recycler_view_train)
    RecyclerView mRecyclerView;

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout mRefreshLayout;

    @BindView(R.id.ll_empty)
    LinearLayoutCompat llEmpty;
    private boolean mIsFirstLoad = true;// 是否第一次，处理懒加载

    private int pagesize = 10;
    private int pagenum =1;
    private int totalPage = 1;
    private List<TrainDataBean.DataBean> dataBeanList = new  ArrayList<>();
    private MyTrainAdapter myTrainAdapter;
    private MDividerItemDecoration mItemDecoration;
    private RecyclerViewSkeletonScreen mSkeletonScreen;
    private long mSkeletonShowTime;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_my_train;
    }

    @Override
    protected void initViews() {
        mUnbinder = ButterKnife.bind(this);
        mRefreshLayout.setOnRefreshLoadMoreListener(this);
        mRefreshLayout.setEnableLoadMoreWhenContentNotFull(false);
     //   getMyTrainList();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        myTrainAdapter = new MyTrainAdapter(this,dataBeanList);
        mRecyclerView.setAdapter(myTrainAdapter);
        mItemDecoration = new MDividerItemDecoration(getContext());
        MColorDrawable colorDrawable = new MColorDrawable(CompatHelper.getColor(R.color.gray_999999));
        colorDrawable.setIntrinsicWidth(1).setIntrinsicHeight(1);
        mItemDecoration.setDrawable(colorDrawable);
        mItemDecoration.setShowLast(true);
    }
    private Gson mGson = new Gson();

    private void getMyTrainList(){
        if(BaseApplication.getContext().getDataLogin()==null){
            return;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("appKey", Constant.TRAIN_APP_KEY);
        params.put("orgId", BaseApplication.getContext().getDataLogin().getCurrentOrg());
        params.put("pageNum", pagenum);
        params.put("pageSize", pagesize);
        params.put("userId", BaseApplication.getContext().getDataLogin().getUser().getId());

        String json = mGson.toJson(params);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        addDisposable(RetrofitService.getNetService()
                .getUserTrainList(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (pagenum == 1) {
                        mRefreshLayout.finishRefresh();
                    } else {
                        mRefreshLayout.finishLoadMore();
                    }
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        totalPage = response.getData().getTotalPage();
                        dataBeanList.addAll(response.getData().getData());
                        myTrainAdapter.notifyDataSetChanged();

                        /*if(dataBeanList.size()==0){
                            llEmpty.setVisibility(View.VISIBLE);
                            mRecyclerView.setVisibility(View.GONE);
                        }else{
                            llEmpty.setVisibility(View.GONE);
                            mRecyclerView.setVisibility(View.VISIBLE);
                        }*/
                        isVisible(myTrainAdapter.getItemCount() > 0);

                    }
                    hideSkeleton();
                }, throwable -> {
                    throwable.printStackTrace();
                    //Tips.RequestError(getActivity());
                    if (pagenum == 1) {
                        mRefreshLayout.finishRefresh();
                    } else {
                        mRefreshLayout.finishLoadMore();
                    }
                    hideSkeleton();
                }));
    }

    private void isVisible(boolean flag){
        if (mRecyclerView.getAdapter() instanceof MyTrainAdapter) {
            if(flag){
                mRecyclerView.setVisibility(View.VISIBLE);
                llEmpty.setVisibility(View.GONE);
            }else{
                llEmpty.setVisibility(View.VISIBLE);
                mRecyclerView.setVisibility(View.GONE);
            }
        }
    }

    private void showSkeleton() {
        mRefreshLayout.setEnableRefresh(false);
        mSkeletonScreen = Skeleton.bind(mRecyclerView)
                .adapter(myTrainAdapter)
                .shimmer(true)
                .shimmerMode(RecyclerViewSkeletonScreen.SHIMMER_MODE_ITEM_CHILD)
                .angle(15)
                .frozen(true)
                //.color(R.color.black_333333)
                .duration(1000)
                .count(10)
                .load(R.layout.item_list_curriculum_skeleton)
                .show();
        ViewCompat.setPaddingRelative(mRecyclerView, DisplayUtil.dip2px(16), 0, DisplayUtil.dip2px2(16), 0);
        mRecyclerView.addItemDecoration(mItemDecoration);
        mSkeletonShowTime = System.currentTimeMillis();
    }

    private void hideSkeleton() {
        if (mSkeletonScreen != null) {
            long currentTime = System.currentTimeMillis();
            if (currentTime - mSkeletonShowTime > Constant.MIN_NETWORK_TIME) {
                mRefreshLayout.setEnableRefresh(true);
                mSkeletonScreen.hide();
                mSkeletonScreen = null;
                ViewCompat.setPaddingRelative(mRecyclerView, 0, 0, 0, 0);
                mRecyclerView.removeItemDecoration(mItemDecoration);
                isVisible(myTrainAdapter.getItemCount() > 0);
            } else {
                addDisposable(Observable.timer(mSkeletonShowTime + Constant.MIN_NETWORK_TIME - currentTime, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(aLong -> hideSkeleton()));
            }
        }
    }

    @Override
    protected int getTitleStringRes() {
        return R.string.my_train;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mIsFirstLoad) {
            mIsFirstLoad = false;
            //mRefreshLayout.autoRefresh();
            onRefresh(mRefreshLayout);
            showSkeleton();
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        if(totalPage>=pagenum+1){
            pagenum++;
            getMyTrainList();
        }else{
            mRefreshLayout.finishLoadMore();
            mRefreshLayout.setEnableLoadMore(false);
        }

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mRefreshLayout.setEnableLoadMore(true);
        pagenum = 1;
        dataBeanList.clear();
        getMyTrainList();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode!= Activity.RESULT_OK){
            return;
        }
        if(requestCode==110){
            mRefreshLayout.autoRefresh();
        }
    }
}
